using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using UnityEngine;

public class FoodScoreManager : MonoBehaviour
{
    public static FoodScoreManager Instance { get; private set; }
    private static Dictionary<int, int> foodScoreMap = new Dictionary<int, int>();
    private const int MAX_TYPE = 30;
    private const string SAVE_KEY = "FOOD_SCORE_DATA";
    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            LoadScoreData();
        }
        else
        {
            Destroy(gameObject);
        }
    }

    private void LoadScoreData()
    {
        string jsonData = PlayerPrefs.GetString(SAVE_KEY, "");
        if (string.IsNullOrEmpty(jsonData))
        {
            for (int i = 1; i < MAX_TYPE; i++)
            {
                foodScoreMap[i] = 1;
            }
            SaveScoreData();
        }
        else
        {
            JObject jObject = JObject.Parse(jsonData);
            foodScoreMap = jObject.ToObject<Dictionary<int, int>>();
        }
    }

    private void SaveScoreData()
    {
        JObject jObject = JObject.FromObject(foodScoreMap);
        string jsonData = jObject.ToString();
        PlayerPrefs.SetString(SAVE_KEY, jsonData);
        PlayerPrefs.Save();
        Debug.Log("保存分数数据: " + jsonData);
    }

    public int GetScoreByType(int type)
    {
        if (type < 0 || type >= MAX_TYPE || !foodScoreMap.ContainsKey(type))
        {
            return 1;
        }
        return foodScoreMap[type];
    }

    public bool ScoreUp(int type)
    {
        if (type < 0 || type >= MAX_TYPE)
        {
            Debug.LogError($"Invalid type: {type}");
            return false;
        }

        if (!foodScoreMap.ContainsKey(type))
        {
            foodScoreMap[type] = 1;
        }

        foodScoreMap[type] += 1;
        SaveScoreData();
        LoadScoreData();
        GlobalEventManager.EmitEvent<int>("FoodTypeUpgradeEvent", type);
        PlayerPrefs.SetInt("MenuRedDot", 1);
        GlobalEventManager.EmitEvent("EliminateRedDots");
        return true;
    }
}
